package com.haiyou.dc.aggregate.list;

import com.google.common.base.Joiner;

/**
 * 实现扩容
 *
 * @param <E>
 */
public class MyArrayList03<E> {

    private Object[] elementData;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

    public MyArrayList03() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    public MyArrayList03(int size) {
        this.elementData = new Object[size];
    }

    public void add(E element) {

        if (size == elementData.length) {
            Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];
            //数组拷贝，将原数组从0开始拷贝到新数组，从0开始，拷贝长度为原数组长度
            System.arraycopy(elementData, 0, newArray, 0, elementData.length);
            //新数组指向老数组
            elementData = newArray;
        }

        elementData[size++] = element;
    }

    @Override
    public String toString() {
        Joiner joiner2 = Joiner.on(",").skipNulls(); //过滤null
        return joiner2.join(elementData);
    }

    public static void main(String[] args) {
        MyArrayList03<Integer> myArrayList01 = new MyArrayList03(20);
        myArrayList01.add(1);
        myArrayList01.add(4);
        System.out.println(myArrayList01);

        for (int i = 0; i < 400; i++) {
            myArrayList01.add(i);
        }

        System.out.println(myArrayList01);
    }
}
